
package andre.grids.db;

import andre.grids.db.exceptions.DbDuplicatedEntry;
import andre.grids.db.dataclasses.*;
import com.db4o.*;
import java.util.*;

/**
 *
 * @author andre
 */
public class DbPeerQueries extends DbQueries {
    public DbPeerQueries()
    {
        super.setDb(Database.getGridFsDb());
    }
    
    public DbPeer getPeerByName(String peerName)
    {
        try
        {
            DbPeer template= new DbPeer();
            template.setPeerName(peerName);
            
            Object value = super.getSingleObjectByPrototype(template, false);
            if (value == null)
                return null;
            return (DbPeer)value;
        }
        catch(DbDuplicatedEntry e)
        {
            andre.grids.util.log.Log.logException(e, this);
        }
        return null;
    }
    
    public Vector<DbPeer> getDirectoryMasters()
    {
        DbPeer peer = new DbPeer();
        peer.setDirectoryMaster(true);
        ObjectSet<DbPeer> set = super.getObjectListByPrototype(peer);
        if (set == null)
            return null;
        Vector<DbPeer> list = new Vector<DbPeer>(set.size());
        while(set.hasNext())
        {
            list.add(set.next());
        }
        return list;
    }
    
    public Vector<DbPeer> getFileServers() {
        DbPeer template = new DbPeer();
        template.setDirectoryMaster(false);
        template.setFileReplica(true);
        
        ObjectSet set = super.getObjectListByPrototype(template);
        if (set == null)
            return null;
        Vector<DbPeer> list = new Vector<DbPeer>(set.size());
        while(set.hasNext())
            list.add((DbPeer)set.next());
        return list;
    }
    
    public static DbPeer getNewOrFromDb(String name) {
        DbPeerQueries query = new DbPeerQueries();
        DbPeer result = query.getPeerByName(name);
        
        if (result == null) {
            result = new DbPeer();
            result.setPeerName(name);
        }
        
        return result;
    }
}
